<script setup lang="ts">
import { useMemberStore } from '@/stores'
import type { goodsListItem } from '@/types/goods'
import { ref, reactive } from 'vue'
import { fullUrl, checkImage } from '@/utils/common'
import { getShareInfoApi } from '@/api/goods'
import { getShareUrl } from './sharePoster'

const props = defineProps<{
  goods: goodsListItem
}>()

const sharePosterRef = ref()

const state = reactive({
  posterImgPath: '',
  showPoster: false,
  userAvatarImg: useMemberStore().profile?.avatar,
  qrcodeUrl: '',
})

const open = async () => {
  await checkImage(fullUrl(useMemberStore().profile!.avatar))
    .then((url) => {
      state.userAvatarImg = url
    })
    .catch(() => {
      state.userAvatarImg = '/static/images/default_avatar.png'
    })

  const shareInfo = await getShareInfoApi(props.goods.id)
  state.qrcodeUrl = shareInfo.result.qrcode_url

  await sharePosterRef.value?.open()
  state.showPoster = true
  state.posterImgPath = ''

  await uni.showLoading({
    title: '海报生成中…',
    mask: true,
  })
}

const close = () => {
  sharePosterRef.value.close()

  state.showPoster = false
}

const onDone = () => {}

const onSuccess = (imgPath: string) => {
  setTimeout(() => {
    state.posterImgPath = imgPath
    uni.hideLoading()
  }, 500)
}

const onSave = () => {
  // #ifdef MP-WEIXIN
  uni.saveImageToPhotosAlbum({
    filePath: state.posterImgPath,
    success: (success) => {
      uni.showToast({
        title: '保存成功',
        icon: 'none',
      })
    },
    fail: (err) => {
      console.log(err)
      if (err.errMsg == 'saveImageToPhotosAlbum:fail cancel') {
        return uni.showToast({
          title: '取消保存',
          icon: 'none',
        })
      } else {
        uni.showToast({
          title: '保存失败',
          icon: 'none',
        })
      }
    },
    complete: () => {
      close()
    },
  })
  // #endif
}

defineExpose({ sharePosterRef, open, close })
</script>

<template>
  <uni-popup ref="sharePosterRef" type="center" :animation="false" :mask-click="false">
    <image :src="state.posterImgPath" mode="widthFix" style="width: 700rpx" />
    <view v-if="state.showPoster">
      <view class="poster">
        <l-painter
          isCanvasToTempFilePath
          @success="onSuccess"
          css="width: 750rpx; padding-bottom: 40rpx; background: #edca88;"
          hidden
          @done="onDone"
          :after-delay="500"
          pathType="url"
        >
          <l-painter-image
            :src="state.userAvatarImg"
            css="margin-left: 40rpx; margin-top: 40rpx; width: 100rpx;  height: 100rpx; border-radius: 50%;"
          />
          <l-painter-view css="margin-top: 40rpx; padding-left: 20rpx; display: inline-block">
            <l-painter-text
              :text="useMemberStore().profile?.nickname || ''"
              css="display: block; padding-bottom: 20rpx; color: #000; font-size: 32rpx; fontWeight: bold"
            />
            <l-painter-text text="推荐了一个好物给您" css="color: #000; font-size: 24rpx" />
          </l-painter-view>
          <l-painter-view
            css="margin-left: 40rpx; margin-top: 30rpx; padding: 32rpx; box-sizing: border-box; background: #fff; border-radius: 16rpx; width: 670rpx; box-shadow: 0 20rpx 58rpx rgba(0,0,0,.15)"
          >
            <l-painter-image
              :src="fullUrl(props.goods.images[0])"
              css="object-fit: cover; object-position: 50% 50%; width: 600rpx; height: 500rpx; border-radius: 12rpx;"
            />
            <l-painter-view
              css="margin-top: 32rpx; color: #FF0000; font-weight: bold; font-size: 28rpx; line-height: 1em;"
            >
              <l-painter-text text="￥" css="vertical-align: bottom" />
              <l-painter-text
                :text="`${props.goods.min_price.split('.')[0]}`"
                css="vertical-align: bottom; font-size: 58rpx"
              />
              <l-painter-text
                :text="`.${props.goods.min_price.split('.')[1]}`"
                css="vertical-align: bottom"
              />
              <l-painter-text
                :text="`￥${props.goods.max_origin_price}`"
                css="vertical-align: bottom; padding-left: 10rpx; font-weight: normal; text-decoration: line-through; color: #999999"
              />
            </l-painter-view>
            <l-painter-view css="margin-top: 30rpx">
              <l-painter-text
                :text="props.goods.name"
                css="line-clamp: 2; color: #333333; line-height: 1.5em; width: 620rpx; font-size: 30rpx; padding-right:32rpx; box-sizing: border-box"
              ></l-painter-text>
            </l-painter-view>
            <l-painter-view css="margin-top: 30rpx; display: flex; flex-wrap: nowrap;">
              <l-painter-text
                text="长按或扫一扫识别二维码"
                css="float: left; padding-bottom: 10rpx; color: #999999; font-size: 26rpx; margin-top: 60rpx; margin-right: 160rpx"
              />
              <!-- #ifdef MP-WEIXIN -->
              <l-painter-image
                v-if="state.qrcodeUrl"
                :src="state.qrcodeUrl"
                css="float: right; width: 150rpx; height: 150rpx;"
              />
              <!-- #endif -->
              <!-- #ifdef WEB -->
              <l-painter-qrcode
                :text="getShareUrl(props.goods.id)"
                css="float: right; width: 150rpx; height: 150rpx;"
              />
              <!-- #endif -->
            </l-painter-view>
          </l-painter-view>
        </l-painter>
      </view>
      <view class="action" v-if="state.posterImgPath">
        <view class="button cancel" @tap="close()">取消分享</view>
        <!-- #ifdef WEB -->
        <view>长按图片进行保存</view>
        <!-- #endif -->
        <!-- #ifdef MP-WEIXIN -->
        <view class="button" @tap="onSave()">保存图片</view>
        <!-- #endif -->
      </view>
    </view>
  </uni-popup>
</template>

<style lang="scss" scoped>
.action {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx;
  background: #f5f5f5;

  .button {
    padding: 16rpx 32rpx;
    margin: 0 10rpx;

    background: #ff784d;
    color: #ffffff;

    border-radius: 40rpx;

    &:active {
      opacity: 0.8;
    }
  }

  .cancel {
    background: #b3b3b3;
    color: #ffffff;
  }
}
</style>
